<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="controlPosition"
      :positionName="positionName"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    >
     <template #add ><el-button @click="addHeader" v-permission="'product/create'" color="#50BC58"  icon="Plus" circle class="ml-4 button"></el-button></template>
    <template #DataImport >
        <el-button class="ml-10 button" :disabled="delsable" color="#F7B32B" @click="haltSales" >
         <div class="flex items-center">
           <img src="@/assets/icon/sales.png" alt="">
          <div class="ml-[10px]"> 批量停售</div>
         </div> 
        </el-button>
                <el-button class="ml-10 button"  color="#2292A4" @click="Import" >
         <div class="flex items-center">
           <img src="@/assets/icon/import.png" alt="">
          <div class="ml-[10px]"> 數據導入</div>
         </div>
        </el-button>
    </template>
    </TopSearch>
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
      <template #default="{ row, propname }">
        <div v-if="propname === 'cate' || propname === 'pp' || propname === 'dw' || propname ==='gys' ">
            {{row[propname] && row[propname].name ? row[propname].name : row[propname]}}
        </div>
        <div v-if="propname === 'pic'">
            <img :src="row[propname]" alt="">
        </div>
      </template>
      
              <template #search_operate>
            <el-table-column  fixed="right" min-width="200px" label="操作">
              <template #default="scope" >
                <div class="flex justify-around">
                <el-link v-permission="'product/update'"  @click="onRowControlClick(scope.row, 'rowedit')" type="primary" :underline="false" >查看</el-link >
                <el-link @click="onRowControlClick(scope.row, 'rowcopy')" type="primary" :underline="false" >複製</el-link >
                <el-link v-permission="'product/delete'"  @click="onRowControlClick(scope.row, 'rowdel')" type="primary" :underline="false" >刪除</el-link >
                </div>
              </template>
            </el-table-column>
        </template>

    </ProTable>
              <addEdit ref="AddEditref" :echo="echo" 
          :producttypeList="producttypeList"
          :brandList="brandList"
          :supplierList="supplierList"
          :unitList="unitList"
          @addConfirm="addConfirm"
          ></addEdit>
              <FouDialog
      :title="'是否下載學生資料導入格式模板'"
      :width="'30%'"
      v-model:dialogValue="excelDiolog"
    >
      <template #content>
        <div><el-icon><WarningFilled /></el-icon>按照規定excel格式導入，可選擇下載當前模板進行格式對比，避免格式不正確導致數據丟失！注意：凡帶有(必填)字樣信息為必填，不填為空系統默以異常數據處理，帶有(參考)字樣需按照網站現有值進行填寫</div>
      </template>
      <template #footer>
          <el-button size="small" @click="onDownExcel">參考規則 (下載模板)</el-button>
          <el-button size="small" type="primary" @click="onImportExcel">已按照規定規則 (繼續導入)</el-button>
      </template>
    </FouDialog>
      <input v-show="false" type="file" accept=".xlsx,.xls" ref="inputUpload" @change="importExcel" /> 
        <FouDialog
      :title="'導入數據展示'"
      :width="'80%'"
      v-model:dialogValue="excelTableShow"
    >
    <template #content>
        <excelTableList :excelTable="excelTable"></excelTableList>
    </template>
    <template #footer>
          <el-button @click="excelTableShow = false" >取消</el-button>
          <el-button color="#081F42" @click="ImportStudent(excelTable)" >確認導入</el-button>
    </template>
    </FouDialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { elProps, options, controlWidth } from "./index.js";
import { setFormConfig } from "./formConfig";
import addEdit from "./addEdit/index.vue";
import { product,delProduct,producttype,brand,supplier,unit,updateStatusProduct,productExcel } from "@/http/index.js";
import { dayjs } from "element-plus";

 import excelTableList from './excelTable.vue'
import { loading, closeLoading,messageBox,message } from "@/common/function.js";
import bus from '@/common/bus.js'

import * as XLSX from "xlsx";
 import {exportExcel} from '@/common/excel.js'

// import sales from '@/assets/icon/sales.svg'
const echo = ref({});
  const excelData = [
    ['產品名稱(必填)','產品分類(必填)','產品品牌(必填)','單位(必填)','產品供應商(必填)','條形碼(必填)','型號','價格(必填)','成本(必填)','備註','安全量','維修期','介紹'],
    ['產品丫丫','配件', '品牌1', '件', '鞋子供應商', '條碼', '白色', '199.00', '100.00', '備註', '100', '1年','介紹'],
  ]; // 导出的表格名称
// 數據導入
const excelDiolog = ref(false)
const Import = ()=>{
   excelDiolog.value = true
}
const onDownExcel = ()=>{
  exportExcel(excelData,'产品列表.xlsx','产品')
  excelDiolog.value = false
}
const inputUpload = ref('')
const onImportExcel = ()=>{
  inputUpload.value.click()
  excelDiolog.value = false
}
const excelTable = ref([])
const excelTableShow = ref(false)
const importExcel = (file)=>{
      // 获取上传的文件对象
      const { files } = file.target;
      // 通过FileReader对象读取文件
      const fileReader = new FileReader();
      fileReader.onload = (event) => {
        try {
          const { result } = event.target;
          // 以二进制流方式读取得到整份excel表格对象
          const workbook = XLSX.read(result, { type: "binary" });
          let data = []; // 存储获取到的数据
          // 遍历每张工作表进行读取（这里默认只读取第一张表）
          for (const sheet in workbook.Sheets) {
            if (Object.prototype.hasOwnProperty.call(workbook.Sheets,sheet)) {//这是关键的一步，hasOwnPropert要从Object的原型中调用
              // 利用 sheet_to_json 方法将 excel 转成 json 数据
              data = data.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              );
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          console.log(data);
          let arr = []
          //  ['學生姓名(必填)','電話(必填)','登錄名(必填)','密碼(必填)','電子郵箱','學生地址','英文名','學生來源','備註','性別(必填)','狀態','調課次數(必填)','生日',
          //  ['產品名稱(必填)','產品分類(必填)','產品品牌(必填)','單位(必填)','產品供應商(必填)','條形碼(必填)','型號','價格(必填)','成本(必填)','備註','安全量','維修期','介紹'],
          data.forEach(item => {
            let obj = {}
            obj.name = item["產品名稱(必填)"]
            obj.products_type = item["產品分類(必填)"]
            obj.brand = item["產品品牌(必填)"]
            obj.unit = item["單位(必填)"]
            obj.supplier = item["產品供應商(必填)"]
            obj.barcode =item["條形碼(必填)"]
            obj.type = item["型號"] 
            obj.price = item["價格(必填)"]
            obj.cost = item["成本(必填)"]
            obj.remark = item["備註"]
            obj.safety = item["安全量"]
            obj.maintain = item["維修期"]
            obj.introduce = item["介紹"]
            arr.push(obj)
          })
            excelTable.value= arr

          excelTableShow.value = true
        } catch (e) {
          // 这里可以抛出文件类型错误不正确的相关提示
          console.log(e);
          message('文件类型不正确,請刷新後再試',"warning")
          return;
        }
      };
      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files[0]);
}
const ImportStudent = async(e)=>{
  console.log(e);
  const data = await productExcel(JSON.stringify(e))
  console.log(data);
    if (data.code == 200) {
        tableList();
        excelTableShow.value = false
    message('導入產品成功')
  }else{
      message(data.msg,'warning')
    }
}
// 添加編輯彈窗
const AddEditref = ref('');
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  statuss:'狀態',
  name: "產品名稱",
  pic:'產品圖片',
  number: "產品編號",
  cate:'產品類別',
  dw:'產品單位',
  pp:'產品品牌',
  gys:'產品供應商',
  type:'產品型號',
  price:"價格",
  cost:"成本",
  discountprice:'產品折扣價',
  safety:"安全量",
  barcode:'條形碼',
  remark: "備註",
  introduce:'產品介紹',
  create_time: "發佈時間",
};
// 表格顶部操作按钮
const control = ["search", "dels"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);
const searchHeader = (e, type) => {
  Object.assign(obj, e);
  tableList(obj);
};

const dialogValue = ref(false);

const addHeader = async() => {
  loading()
      await  producttypeSelect()
      await  brandSelect()
      await  supplierSelect()
      await  unitSelect()
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = "add"
echo.value = {
    name: "",
    products_type_id: "",//產品分類
    brand_id:'',         //產品品牌
    unit_id:'',          //單位
    barcode: "",
    type: "",
    price: "",
    cost:'',
    remark:'',
    status: "",
    safety:1,
    supplier_id:'',       //供應商
    maintain:'',
    introduce:'',
    numstatus:true,
    discountstatus:false,
}
  dialogValue.value = true;
closeLoading()
};

// 表格行内操作按钮
const rowControl = ["rowedit", "rowcopy", "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const onRowControlClick = async (row, type) => {
  console.log(row,type);
  if (type == "rowedit") {
    loading()
      await  producttypeSelect()
      await  brandSelect()
      await  supplierSelect()
      await  unitSelect()
      closeLoading()
    const { id, name, products_type_id, brand_id, unit_id, barcode,type,price,cost,remark,status,safety,supplier_id,maintain,introduce,numstatus,discountstatus,starttime,endtime,discountprice } = row;
    echo.value ={ id, name, products_type_id, brand_id, unit_id, barcode,type,price,cost,remark,status,safety,supplier_id,maintain,introduce,numstatus,discountstatus,discountprice } 
    if (echo.value.numstatus ==1) {
      echo.value.numstatus = true
    }else{echo.value.numstatus = false }
    if (echo.value.discountstatus ==1) {
      echo.value.discountstatus = true
      echo.value.discounttime = []
      echo.value.discounttime.push(starttime)
      echo.value.discounttime.push(endtime)
    }else{  echo.value.discountstatus = false }
   AddEditref.value.buttonType = "edit"
    AddEditref.value.dialogValue = true;

  }
  if (type == 'rowcopy') {
        loading()
      await  producttypeSelect()
      await  brandSelect()
      await  supplierSelect()
      await  unitSelect()
      closeLoading()
    const { name, products_type_id, brand_id, unit_id, barcode,type,price,cost,remark,status,safety,supplier_id,maintain,introduce,numstatus,discountstatus,starttime,endtime,discountprice } = row;
    echo.value ={  name, products_type_id, brand_id, unit_id, barcode,type,price,cost,remark,status,safety,supplier_id,maintain,introduce,numstatus,discountstatus,discountprice } 
    if (echo.value.numstatus ==1) {
      echo.value.numstatus = true
    }else{echo.value.numstatus = false }
    if (echo.value.discountstatus ==1) {
      echo.value.discountstatus = true
      echo.value.discounttime = []
      echo.value.discounttime.push(starttime)
      echo.value.discounttime.push(endtime)
    }else{  echo.value.discountstatus = false }
   AddEditref.value.buttonType = "copy"
    AddEditref.value.dialogValue = true;

  }
  if (type == 'rowdel') {
        messageBox().then(async () => {
        await delTableList(row.id) 
    })
  }
}
// 刪除產品
const delTableList = async (id)=>{
  const data = await delProduct(id)
  if (data.code == 200) {
    tableList(obj)
    message('成功刪除產品')
  }else{
    message('刪除產品失敗','warning')
  }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
// 批量停售
const haltSales = async()=>{
  const data = await updateStatusProduct(ids.value)
  console.log(data);
  if (data.code == 200) {
    tableList(obj)
  }
}
const delsHeader = () => {
    messageBox().then(async () => {
        await delTableList(ids.value) 
    })
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async ({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};
const tableData = ref([])
const obj = reactive({
  // school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableList = async ()=>{
  loading()
  const data = await product(obj)
  if (data.code == 200) {
    data.data.data.map(e=>e.status == 1 ?  e.statuss = '發售中' :    e.statuss = '停售')
    tableData.value = data.data.data
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    console.log( tableData.value);
  }
  closeLoading()
}
const producttypeList = ref([])
const brandList = ref([])
const supplierList = ref([])
const unitList = ref([])
const objs = {limit:100}
const producttypeSelect = async ()=>{
    const data = await producttype(objs)
    if (data.code == 200) {
     producttypeList.value = data.data.data
    }
}
const brandSelect = async ()=>{
    const data = await brand(objs)
       if (data.code == 200) {
     brandList.value = data.data.data
    }
}
const supplierSelect = async ()=>{
    const data = await supplier(objs)
        if (data.code == 200) {
     supplierList.value = data.data.data
    }
}
const unitSelect = async ()=>{
    const data = await unit(objs)
        if (data.code == 200) {
     unitList.value = data.data.data
    }
}

const pageRefresh = async () => {
  await tableList(obj);
};
const addConfirm = ()=>{
    tableList(obj);
}
onMounted(() => {
  tableList(obj);
  producttypeSelect()
});

</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
.button{
  color: #fff;
}
</style>